package com.solution.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取分页页码
 * @author suwang
 * @date 2017年5月23日 下午2:54:50
 */
public class PaginationUtils {

	public static List<Integer> getPaginationItems(int pageMargin, int currentPage, int totalPageCount) {
		List<Integer> pageItems = new ArrayList<Integer>();
		if(pageMargin < 1){
			throw new IllegalArgumentException("'pageMargin' can not less than 1!");
		}
		if(currentPage < 1){
			throw new IllegalArgumentException("'currentPage' can not less than 1!");
		}
		if(totalPageCount < 0){
			throw new IllegalArgumentException("'totalPageCount' can not less than 0!");
		}
		if(totalPageCount < currentPage){
			return pageItems;
		}
		int start = currentPage - pageMargin;
		int end = currentPage + pageMargin;
		if(start <= 0){
			int offset = Math.abs(start) + 1;
			start = start + offset;
			end = end + offset;
		}
		if(end > totalPageCount){
			int offset = totalPageCount - end;
			end = end + offset;
			start = start + offset;
			start = start < 1 ? 1 : start;
		}
		for(int i = start; i <= end; i++){
			if(i == start && i > 1){ //first
				pageItems.add(1);
				if(i - 1 > 2){
					pageItems.add(null);
				}else if(i - 1 == 2){
					pageItems.add(i - 1);
				}
			}
			pageItems.add(i);
			if(i == end && i < totalPageCount){ //last
				if(totalPageCount - end > 2){
					pageItems.add(null);
				}else if(totalPageCount - end == 2){
					pageItems.add(totalPageCount - 1);
				}
				pageItems.add(totalPageCount);
			}
		}
		return pageItems;
	}

}
